import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Microsoft
 * Date: 2023-04-21
 * Time: 18:17
 */


public class JDBCInsert {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        //JDBC需要通过以下步骤来完成开发
        //1. 创建并初始化一个数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java107?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");
        //MysqlDataSource mysqlDataSource = new MysqlDataSource();
        //2. 和数据库服务器建立连接
        //java.sql下的Connection
        Connection connection = dataSource.getConnection();

        //3. 从控制台读取用户的输入内容
        System.out.println("请输入学生姓名：");
        String name = scanner.nextLine();
        System.out.println("请输入学号：");
        int id = scanner.nextInt();

        //4. 构造SQL语句
        String sql = "insert into student value(?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        System.out.println(statement);
        statement.setInt(1,id);
        statement.setString(2,name);
        System.out.println(statement);
        //5. 执行SQL语句
        int ret = statement.executeUpdate();//把sql语句发送给数据库服务器，由服务器做出响应
        /*我们sql中的insert delete update 最终都是通过executeUpdate进行发送，返回int类型数值，表示所影响的行数,select使用executeQuery更复杂一点以后再说*/
        System.out.println("ret = "+ret);

        //6. 释放必要的资源
        statement.close();
        connection.close();

    }
}

